﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"


//实现初始化
void LTInit(ListNode** pphead)
{
	*pphead = LTBuyNode(0);
}

//创建节点
ListNode* LTBuyNode(dataClass x)
{
	ListNode* ret = (ListNode*)malloc(sizeof(ListNode));
	if (ret == NULL) exit(-1);
	ret->data = x;
	ret->prev = ret->next = ret;
	return ret;
}

//实现尾插
void LTPushBack(ListNode* sentry, dataClass x)
{
	assert(sentry);
	ListNode* last = sentry->prev;
	ListNode* newNode = LTBuyNode(x);
	last->next = sentry->prev = newNode;
	newNode->prev = last;
	newNode->next = sentry;
}

//实现头插
void LTPushFront(ListNode* sentry, dataClass x)
{
	assert(sentry);
	ListNode* newNode = LTBuyNode(x);
	sentry->next->prev = newNode;
	newNode->next = sentry->next;
	newNode->prev = sentry;
	sentry->next = newNode;
}

//打印
void LTPrint(ListNode* sentry)
{
	assert(sentry);
	ListNode* str = sentry->next;
	while (str != sentry)
	{
		printf("%d ", str->data);
		str = str->next;
	}
	printf("\n");
}

//尾删
void LTPopBack(ListNode* sentry)
{
	assert(sentry && sentry->next != sentry);
	ListNode* last = sentry->prev;
	last->prev->next = sentry;
	sentry->prev = last->prev;
	free(last);
}

//头删
void LTPopFront(ListNode* sentry)
{
	assert(sentry && sentry->next != sentry);
	ListNode* first = sentry->next;
	sentry->next = first->next;
	first->next->prev = sentry;
	free(first);
}

//在指定位置之后插入数据
void LTInsert(ListNode* pos, dataClass x)
{
	assert(pos);
	ListNode* newNode = LTBuyNode(x);
	newNode->prev = pos;
	newNode->next = pos->next;
	pos->next->prev = newNode;
	pos->next = newNode;
}

//查找
ListNode* LTFind(ListNode* sentry, dataClass x)
{
	assert(sentry);
	ListNode* str = sentry->next;
	while (str != sentry)
	{
		if (str->data == x) return str;
		str = str->next;
	}
	return NULL;
}

//删除节点
void LTErase(ListNode* pos)
{
	assert(pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
}

//销毁链表
void LTDesTroy(ListNode* sentry)
{
	assert(sentry);
	ListNode* str = sentry->next;
	ListNode* rem = str;
	while (str != sentry)
	{
		rem = str->next;
		free(str);
		str = rem;
	}
	free(str);
}